package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录接口
     * @param employee
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("接收到登录信息：{}", employee);
        //1. 密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        log.info("加密后的密码：{}", password);

        //2. 根据用户名获取用户信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(employee.getUsername() != null, Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(lqw);

        //3. 判断用户是否存在
        if (one == null) {
            log.info("用户名不存在");
            return R.error("用户名不存在");
        }

        //4. 判断密码是否一致
        if (!one.getPassword().equals(password)) {
            log.info("密码错误");
            return R.error("密码错误");
        }

        //5. 判断权限，状态
        if (one.getStatus() == 0) {
            log.info("账号已被禁用");
            return R.error("账号已被禁用");
        }

        //6. 登录成功 - 把哟用户信息存入会话范围 (emp empId)
        HttpSession session = request.getSession();
        session.setAttribute("empId", one.getId());

        //7. 给出响应
        return R.success(one);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        //清理Session中保存的当前员工的id
        request.getSession().removeAttribute("empId");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工信息: {}", employee.toString());
        //封装数据（status\password\字段）
        //加密密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));

       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/

        //获取当前用户登录的id
        Long empId = (Long) request.getSession().getAttribute("empId");

        /*employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        //数据库新增
        boolean b = employeeService.save(employee);
        //给出响应
        return b ? R.success("新增员工成功") : R.error("新增员工失败");
    }

//    @PathVariable  --/1
//    @ResponseBody  -- JSON
//    @RequestParam  可以省略

    /**
     * 员工信息分页查询
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @param name     员工姓名 - 可选参数
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam Integer page, Integer pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        //构造分页构造器
        Page<Employee> pageInfo = new Page<Employee>(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null, Employee::getName, name);
        //添加排序条件
        lqw.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 修改员工信息
     * @param session
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpSession session, @RequestBody Employee employee) {
        //1. 接收参数
        log.info("修改的emp为：{}", employee);
        //2. 更新字段修改的人，修改时间
        Long empId = (Long) session.getAttribute("empId");

       /* employee.setUpdateTime(LocalDateTime.now());

        employee.setUpdateUser(empId);*/

        //3. 修改
        boolean b = employeeService.updateById(employee);

        return b ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 把数据信息投影到修改框中
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id{}查询信息", id);
        Employee employee = employeeService.getById(id);

        return employee != null ? R.success(employee) : R.error("没有查询到对应员工信息");
    }

}
